package domain;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

import java.io.*;

public class NewsManager {

    public static void main(String[] args){
        //最简单的使用
//        SessionFactory sf = new Configuration().configure().buildSessionFactory();

        StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
                .configure()
                .build();
        //代码中指定注解的类
//        Metadata metadata = new MetadataSources( standardRegistry )
//                .addAnnotatedClass( News.class )
//                .getMetadataBuilder()
//                .applyImplicitNamingStrategy( ImplicitNamingStrategyJpaCompliantImpl.INSTANCE )
//                .build();
//
//        SessionFactory sf = metadata.getSessionFactoryBuilder().build();


        SessionFactory sf = new Configuration().configure().buildSessionFactory(standardRegistry);
        Session session = sf.openSession();
        Transaction tx= session.beginTransaction();

//        News n = new News();
//        n.setTitle("titleA");
//        n.setContent("www.zz.com");
//        n.setSeason(Season.Spring);
//        File file = new File("web/image/gakki.jpg");
//        byte[] content = new byte[(int)file.length()];
//        try {
//            new FileInputStream(file).read(content);
//            n.setPic(content);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        session.save(n);
        tx.commit();
        session.close();

        Session session1 = sf.openSession();
        News n2 = session1.get(News.class, "ff8081815cf8dbff015cf8dc01380000");
        System.out.println(n2);
        System.out.println(n2.getFullContent());
        System.out.println(n2.getSeason());
        System.out.println(n2.getTimestamp());
        System.out.println(n2.getUuid());

//        File file1 = new File("web/image/a.jpg");
//        try {
//            new FileOutputStream(file1).write(n2.getPic());
//        } catch (IOException e) {
//            e.printStackTrace();
//        }

        session1.close();
        sf.close();

    }

}
